<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\Course as CourseModel;
use app\common\model\CourseQuestion;
use think\Db;

class Question extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     * 题目详情页面
     * @param int $id 题目ID
     * @return mixed
     */
    public function detail($id = 0)
    {
        if (empty($id)) {
            $this->error('题目ID不能为空');
        }

        // 查询题目详细信息
        $question = CourseQuestion::getQuestionDetail($id);

        if (!$question) {
            $this->error('题目不存在');
        }

        // 解析题目数据
        $questionData = json_decode($question['question_data'], true);
        
        // 格式化题目信息
        $questionInfo = [
            'id' => $question['id'],
            'title' => $question['question_name'],
            'course_name' => $question['course_name'],
            'course_code' => $question['course_code'],
            'exam_name' => $question['exam_name'],
            'type' => $this->getQuestionTypeName($question['question_type']),
            'charge_type' => $question['charge_type'] == 1 ? '免费' : '收费',
            'question_ask' => $questionData['questionAsk'] ?? '',
            'answer_options' => $questionData['answerOption'] ?? [],
            'correct_option' => $questionData['correctOption'] ?? '',
            'explanation' => $questionData['explanation'] ?? '',
            'upload_time' => date('Y-m-d H:i:s', $question['a_time']),
            'update_time' => date('Y-m-d H:i:s', $question['u_time'])
        ];

        // 获取相关题目推荐（同课程的其他题目）
        $relatedQuestions = CourseQuestion::getRelatedQuestions($question['course_id'], $id, 5);

        // 格式化相关题目
        $relatedList = [];
        foreach ($relatedQuestions as $item) {
            $relatedList[] = [
                'id' => $item['id'],
                'title' => $item['question_name'],
                'type' => $this->getQuestionTypeName($item['question_type'])
            ];
        }

        $this->view->assign([
            'question' => $questionInfo,
            'relatedQuestions' => $relatedList
        ]);

        return $this->view->fetch();
    }

    /**
     * 获取题目类型名称
     * @param int $type
     * @return string
     */
    private function getQuestionTypeName($type)
    {
        $types = [
            1 => '单选题',
            2 => '多选题', 
            3 => '判断题',
            4 => '问答题',
            5 => '填空题',
            6 => '完形填空',
            7 => '阅读理解',
            8 => '名词解释'
        ];
        
        return $types[$type] ?? '未知类型';
    }
}